/*
 * Copyright 2012 Gayan Perera
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/
package gap.maven.script;
import gap.maven.script.annotation.DependencyFetcher;
import gap.maven.script.components.ComponentContext;
import gap.maven.script.components.DefaultScriptContext;
import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;
import groovy.util.ResourceException;
import groovy.util.ScriptException;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.PluginManager;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectBuilder;

/**
 * @author gayan
 * 
 * @goal run
 * @requiresProject false
 */
public class RunMojo extends AbstractMojo {

    /** @component */
    private ArtifactFactory factory;

    /** @component */
    private ArtifactResolver resolver;

    /** @parameter default-value="${localRepository}" */
    private ArtifactRepository localRepository;

    /** @parameter default-value="${project.remoteArtifactRepositories}" */
    @SuppressWarnings("rawtypes")
    private List remoteRepositories;

    /** @component */
    private MavenProjectBuilder projectBuilder;
    
    
    /**
     * @parameter default-value="${user.home}/scripts/"
     * expression="${scriptDir}"
     */
    private File scriptDir;

    /**
     * @parameter
     * expression="${script}"
     * @required
     */
    private String script;
    
    
    /**
     * @parameter
     * expression="${project}"
     */
    private MavenProject project;
    
    
    /**
     * The Maven Session Object
     *
     * @parameter expression="${session}"
     * @required
     * @readonly
     */
    protected MavenSession session;

    /**
     * The Maven PluginManager Object
     *
     * @component
     * @required
     */
    protected PluginManager pluginManager;   

    public void execute() throws MojoExecutionException, MojoFailureException {
        try {
            final ComponentContext context = new ComponentContext(getLog(), factory, resolver, projectBuilder,
                    localRepository, remoteRepositories, session, pluginManager);
            final DefaultScriptContext scriptContext = new DefaultScriptContext(context, project);
            final GroovyScriptEngine engine = new GroovyScriptEngine(scriptDir.getPath());
            final Binding binding = new Binding();
            binding.setVariable("log", getLog());
            binding.setVariable("context", scriptContext);
            
            if (!script.endsWith(".groovy")) {
                script += ".groovy";
            }

            // adding the dependency fetcher to compilation phase.
            engine.getConfig().addCompilationCustomizers(new DependencyFetcher(scriptContext, getLog()));
            engine.run(script, binding);
        } catch (IOException ex) {
            throw new MojoFailureException("Error initializing script engine.", ex);
        } catch (ResourceException ex) {
            throw new MojoFailureException("Error running script.", ex);
        } catch (ScriptException ex) {
            throw new MojoFailureException("Error running script.", ex);
        }

    }

}
